<script setup >
// import * as Cesium from 'cesium'
import { onMounted, ref } from "vue";
import {
  KyViewer,
  Line,
  Marker,
  MarkerStyle,
  PolygonCube,
  PolygonStyle,
  Tileset,
} from "../plugins/cesium/index";
import AmapImageryProvider from "../plugins/imagery/amap/AmapImageryProvider.js";
import { lines } from "./lines.js";
import "../plugins/cesium/material/index.js";
import arrowImg from "../assets/arrow.png";
// import lamina from '../assets/lamina.gpx'
import img from "../assets/trackPerson.png";
import {
  formatDate,
  initBillBordByEntity,
  initBillBordByPrimitive,
  initPointByEntity,
  initPointByPrimitive,
} from "../utils";

let kyViewer = null;
let entity = null;
let tileset = null;
// 两个点间的时间间隔，s
const timeInterval = 3;
const start = Cesium.JulianDate.fromDate(new Date());
const stop = Cesium.JulianDate.addSeconds(
  start,
  timeInterval * (lines.length - 1),
  new Cesium.JulianDate(),
);
const interType = ref(2);
const interValue = ref(2);
onMounted(() => {
  initMap();
});

const tileSetUrl = "/tile/jingzhou/yushui/tileset.json";

function initMap() {
  // 官网申请的Token
  Cesium.Ion.defaultAccessToken =
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIxZWVkZGUxZC1hOTUxLTRiN2UtODgwNC01NTU5NGE3N2E5OTMiLCJpZCI6OTE1NzUsImlhdCI6MTY1MTExNjMwMX0._Zy9FObZndU-FXugY1UkGJMwlCmB4jSN1Yk-_5rdw5s";

  kyViewer = new KyViewer("cesiumContainer", {
    animation: false,
    shouldAnimate: true,
    timeline: false,
  });
  // 展示帧数延迟
  kyViewer.scene.debugShowFramesPerSecond = true;
  tileset = new Tileset(tileSetUrl, kyViewer, {
    maximumScreenSpaceError: 256,
  });
  kyViewer.zoomTo(tileset);
  // 在 tileset.onLoad 回调中添加以下代码
  tileset.onLoad(() => {
    // // 设置模型为纯色，不响应光照
    // tileset.style = new Cesium.Cesium3DTileStyle({
    //   color: {
    //     conditions: [
    //       ["true", "rgba(0, 170, 255, 1)"], // 设置为蓝色（可自定义）
    //     ],
    //   },
    //   // 关闭光照相关属性
    //   brightness: 1.0,
    //   contrast: 1.0,
    //   emissive: "rgba(0, 170, 255, 1)", // 发光颜色，使模型看起来像“发光”
    //   // 可选：关闭法线贴图和高光等
    //   // normalMap: null,
    //   // specular: "rgba(0, 0, 0, 0)",
    // });

    // 如果你想完全忽略光照，也可以直接设置为纯色且无任何光照响应
    tileset.style = new Cesium.Cesium3DTileStyle({
      color: {
        conditions: [["true", "rgba(0, 170, 255, 1)"]],
      },
    });
  });
  // tileset.onLoad(() => {
  //   tileset.MoveByCartographic(111.2043, 30.6832, -2);
  //   tileset.rotateByDegree({ rz: 25 });
  //   // 让模型半透明
  //   // showTilesetTransParent();
  //   // initPath();
  //   // typeChange();
  //   kyViewer.zoomTo(tileset);
  // });

  // initPath();
  // typeChange();
}

function handleClick() {
  /**
   * 地图引擎的鼠标右键点击事件
   */
  kyViewer.onRightClick((target) => {
    const feature = kyViewer.scene.pick(target.position);
    const heading = kyViewer.camera.heading;
    const pitch = kyViewer.camera.pitch;
    const roll = kyViewer.camera.roll;
    // 相机的经纬坐标
    const carto = kyViewer.camera.positionCartographic;
    const { height, longitude, latitude } = carto;
    const result = {
      height,
      longitude: Cesium.Math.toDegrees(longitude),
      latitude: Cesium.Math.toDegrees(latitude),
      heading,
      pitch,
      roll,
    };
    console.log("相机参数", JSON.stringify(result));

    if (feature === undefined) {
      const cartesian3 = kyViewer.scene.globe.pick(
        kyViewer.camera.getPickRay(target.position),
        kyViewer.scene,
      );
      const cartographic = Cesium.Cartographic.fromCartesian(cartesian3);
      console.log(
        "点击了地形经纬高",
        Cesium.Math.toDegrees(cartographic.longitude),
        Cesium.Math.toDegrees(cartographic.latitude),
        cartographic.height,
      );
    } else {
      const cartesian3 = kyViewer.scene.pickPosition(target.position);
      const cartographic = Cesium.Cartographic.fromCartesian(cartesian3);
      console.log(
        "点击了模型经纬高",
        Cesium.Math.toDegrees(cartographic.longitude),
        Cesium.Math.toDegrees(cartographic.latitude),
        cartographic.height,
      );
    }
  });
}

function initPath() {
  console.log("开始结束时间", start, stop);
  kyViewer.showGlobe();
  kyViewer.clock.startTime = start.clone();
  kyViewer.clock.stopTime = stop.clone();
  kyViewer.clock.currentTime = start.clone();
  kyViewer.clock.multiplier = timeInterval / 2;
  kyViewer.clock.clockRange = Cesium.ClockRange.CLAMPED;
  // 把时间线转换为北京时间
  kyViewer.animation.viewModel.dateFormatter = function (date, viewModel) {
    const localDate = Cesium.JulianDate.toDate(date);
    return formatDate(localDate, "YYYY-MM-DD");
  };
  kyViewer.animation.viewModel.timeFormatter = function (date, viewModel) {
    const localDate = Cesium.JulianDate.toDate(date);
    return formatDate(localDate, "HH:mm:ss");
  };
  kyViewer.timeline.zoomTo(start, stop);

  const position = computeCirclularFlight();
  entity = kyViewer.entities.add({
    availability: new Cesium.TimeIntervalCollection([
      new Cesium.TimeInterval({
        start: start,
        stop: stop,
      }),
    ]),
    position: position,
    // model: {
    //   uri: './Cesium_Air.glb',
    //   minimumPixelSize: 100,
    //   maximumSize: 200,
    //   maximumScale: 200
    // },
    billboard: {
      image: img,
      width: 60,
      height: 94,
      disableDepthTestDistance: 2000,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
    },
    orientation: new Cesium.VelocityOrientationProperty(position),
    path: {
      resolution: timeInterval / 10,
      // leadTime: 0,
      // material: new Cesium.ImageLineMaterialProperty({
      //   image:
      //       '',
      //   duration: 2000,
      //   imageW: 200,
      //   backgroundColor: Cesium.Color.RED
      // }), //修改抛物线材质
      // material: new Cesium.PolylineGlowMaterialProperty({
      //   glowPower: 0.2,
      //   taperPower: 0.2,
      //   color: Cesium.Color.fromCssColorString('#2d0202')
      // }),
      // material: new Cesium.ImageMaterialProperty({
      //   image: arrowImg,
      //   repeat: new Cesium.Cartesian2(100.0, 1.0),
      //   // color: Cesium.Color.fromCssColorString('#FFEA29')
      // }),
      width: 20,
      disableDepthTestDistance: 2000,
    },
  });
  kyViewer.zoomTo(
    entity,
    new Cesium.HeadingPitchRange(0, Cesium.Math.toRadians(-90), 1000),
  );
}

function showTilesetTransParent(alpha = 0.9) {
  tileset.style = new Cesium.Cesium3DTileStyle({
    color: {
      conditions: [["true", `rgba(255,255,255,${alpha})`]],
    },
  });
}

function computeCirclularFlight() {
  const property = new Cesium.SampledPositionProperty();
  let i = 0;
  // const polylinePostions = []
  lines.forEach((item) => {
    const time = Cesium.JulianDate.addSeconds(
      start,
      i,
      new Cesium.JulianDate(),
    );
    i += timeInterval;
    const position = Cesium.Cartesian3.fromDegrees(
      item.longitude,
      item.latitude,
      item.height || 5,
    );
    property.addSample(time, position);
    // polylinePostions.push(position)
    const pointPos = Cesium.Cartesian3.fromDegrees(
      item.longitude,
      item.latitude,
      item.height + 0.5 || 5,
    );
    kyViewer.entities.add({
      position: pointPos,
      point: {
        pixelSize: 10,
        color: Cesium.Color.RED,
        outlineColor: Cesium.Color.YELLOW,
        outlineWidth: 3,
        disableDepthTestDistance: 2000,
      },
    });
  });
  console.log("点个数", lines.length, "用时", i);
  return property;
}

function typeChange() {
  const interDegree = Number(interValue.value);
  if (interType.value == 2) {
    console.log("选择了隐士多项式平滑", interDegree, interValue.value);
    entity.position.setInterpolationOptions({
      interpolationDegree: interDegree,
      interpolationAlgorithm: Cesium.HermitePolynomialApproximation,
    });
  } else if (interType.value == 3) {
    console.log("选择了拉格朗日平滑", interDegree);
    entity.position.setInterpolationOptions({
      interpolationDegree: interDegree,
      interpolationAlgorithm: Cesium.LagrangePolynomialApproximation,
    });
  } else {
    entity.position.setInterpolationOptions({
      interpolationDegree: 12,
      interpolationAlgorithm: Cesium.LinearApproximation,
    });
  }
}
</script>

<template>
  <div id="cesiumContainer"></div>
  <div class="interType">
  <select v-model="interType" @change="typeChange">
    <option :value="1">线性</option>
    <option :value="2">隐士多项式近似</option>
    <option :value="3">拉格朗日多项式近似平滑</option>
  </select>
  <input v-model.number="interValue" @change="typeChange">
  </div>
</template>

<style scoped>
#cesiumContainer {
  width: 100vw;
  height: 100vh;
}

.interType {
  position: absolute;
  width: 200px;
  top: 30px;
  left: 30px;
}
</style>
